const Router = require("koa-router");
const axios = require("axios");

const { Op } = require("sequelize");
const { News } = require("@models/news");
const { Auth } = require("@middlewares/auth");
const { Favor } = require("@models/favor");
const { redis } = require("@core/redis");
const { Admin } = require("@models/admin");

const router = new Router({
  prefix: "/v1/news",
});

// 新闻列表
router.post("/list", async (ctx, next) => {
  const { page = 1, pageSize = 10, title = "" } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = {
    is_del: true,
    title: {
      [Op.like]: `%${title}%`,
    },
  };

  const { count: total, rows } = await News.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    attributes: { exclude: ["content"] }, // 排除字段
    order: [["news_id", "desc"]], // 排序
  });

  // await storeDataToRedis("News", rows, "news_id");

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 新闻详情
router.post("/detail", async (ctx, next) => {
  const { news_id } = ctx.request.body;

  const result = await redis.get(`news:${news_id}`);
  if (result) {
    ctx.body = {
      code: 200,
      msg: "获取成功",
      data: JSON.parse(result),
    };
  }

  if (!result) {
    const news = await News.findOne({
      where: { news_id, is_del: 1 },
      include: [
        {
          model: Admin,
          attributes: ["admin_name", "avatar"],
          required: false,
        },
      ],
    });

    if (!news) {
      throw new global.errs.AuthFailed("查询失败");
    }

    await redis.set(`news:${news_id}`, JSON.stringify(news));
    ctx.body = {
      code: 200,
      msg: "获取成功",
      data: news,
    };
  }
});

router.post("/fav/num", async (ctx) => {
  const { news_id } = ctx.request.body;
  const count_num = await Favor.count({
    where: {
      news_id,
    },
  });

  ctx.body = {
    code: 200,
    msg: "查询成功",
    count_num,
  };
});

module.exports = router;
